﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Directory.Web
{
	public partial class Register : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			ltMsg.Text = "";
		}

		protected void btnRegister_Click(object sender, EventArgs e)
		{
			if (tbPassword.Text != tbVerifyPwd.Text)
			{
				ltMsg.Text = "密码不匹配。";
				return;
			}
			Directory.Model.UserInfo.ErrorCode errorcode;
			try
			{
				UserDataProxy.CreateUser(tbName.Text, tbPassword.Text,tbPassowrdQuestion.Text,tbPasswordAnswer.Text.Trim(), out errorcode);
			}
			catch
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(), null, "<script>alert('服务器错误：未知错误')</script>");
				return;
			}
			switch (errorcode)
			{
				case Directory.Model.UserInfo.ErrorCode.Success:
					RoleDataProxy.AddUserToRole(tbName.Text, WebSettings.GetInstance().CustomRole);
					if (WebUtil.TryLogIn(tbName.Text, tbPassword.Text, false))
					{
						Response.Redirect(FormsAuthentication.DefaultUrl,true);
					}
					else
					{
						FormsAuthentication.RedirectToLoginPage();
					}
					break;
				case Directory.Model.UserInfo.ErrorCode.UserNameAlreadyExists:
					ltMsg.Text = "用户名已被注册";
					break;
				case Directory.Model.UserInfo.ErrorCode.InvalidPassword:
					ltMsg.Text = "密码格式不正确";
					break;
				case Directory.Model.UserInfo.ErrorCode.InvalidUserName:
					ltMsg.Text = "用户名格式不正确";
					break;
				default:
					ltMsg.Text = errorcode.ToString() ;
					break;
			}
		}
	}
}
